package pay

import (
	"context"
	"errors"
	"fmt"
	"strconv"
	"time"

	"github.com/xxl-job/xxl-job-executor-go"

	schema "gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/dao/schema/recharge"
	"gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/svc"
	"github.com/bytedance/sonic"

	"gitee.com/liuxuezhan/ar-platform/base-common/xxlJob"
	"gitee.com/liuxuezhan/ar-platform/rpc-client/setting/rpc"
	"github.com/zeromicro/go-zero/core/logc"
)

type DepositTimeoutHandler struct {
	svcCtx *svc.ServiceContext
}

func NewDepositTimeoutHandler(ctx *svc.ServiceContext) *DepositTimeoutHandler {
	return &DepositTimeoutHandler{
		svcCtx: ctx,
	}
}

func (h DepositTimeoutHandler) Handler() xxlJob.HandlerFun {
	return func(ctx context.Context, param *xxl.RunReq) string {
		if err := UpRechargeOrderTimeoutStatus(ctx, h.svcCtx); err != nil {
			logc.Error(ctx, err)
		}
		return "payTask.deposit_timeout finish..."
	}
}

func (h DepositTimeoutHandler) Pattern() string {
	return "payTask.deposit_timeout"
}

func UpRechargeOrderTimeoutStatus(ctx context.Context, svcCtx *svc.ServiceContext) error {
	// 获取充值超时时间配置
	req := &rpc.DataViewReq{
		MerchantId: 1,
		ModelType:  1,
		Type:       10028,
	}
	resp, err := svcCtx.SettingRpc.DataView(ctx, req)
	if err != nil {
		fmt.Println("Get setting rpc data error: ", err.Error())
		return err
	}
	var m map[string]any
	if err = sonic.UnmarshalString(resp.Data.List[0].Value, &m); err != nil {
		fmt.Println("UnmarshalStrin error: ", err.Error())
		return err
	}
	t, ok := m["top_up"]
	if !ok || t.(float64) == 0 {
		fmt.Println("Recharge timeout not configured")
		return errors.New("Recharge timeout not configured")
	}
	ex, err := strconv.ParseInt(fmt.Sprintf("%.0f", t.(float64)*60), 10, 64)
	if err != nil {
		fmt.Println("strconv.ParseInt error: ", err.Error())
		return err
	}
	// 超时时间戳
	timestamp := time.Now().Add(time.Duration(-ex) * time.Second).Unix()
	// 更新已超时订单状态
	result := svcCtx.Db.Model(&schema.RechargeOrder{}).Where("status = 1 AND created_at < ?", timestamp).Update("status", schema.TimeoutStatus)
	if result.Error != nil {
		fmt.Println("Update recharge order error: ", result.Error.Error())
		return result.Error
	}
	fmt.Println("Update timeout recharge order success, affected rows: ", result.RowsAffected)
	logc.Info(ctx, "Update timeout recharge order success, affected rows: ", result.RowsAffected)
	return nil
}
